package com.ysdz.tibetan.tibetanmini.user.service.impl;

import com.ysdz.tibetan.tibetanmini.user.beans.Auth;
import com.ysdz.tibetan.tibetanmini.user.beans.Consumer;
import com.ysdz.tibetan.tibetanmini.user.beans.Role;
import com.ysdz.tibetan.tibetanmini.user.beans.UserRole;
import com.ysdz.tibetan.tibetanmini.user.dao.AuthMapper;
import com.ysdz.tibetan.tibetanmini.user.dao.RoleMapper;
import com.ysdz.tibetan.tibetanmini.utils.RedisUtils;
import com.ysdz.tibetan.tibetanminicommons.common.ReturnMsg;
import com.ysdz.tibetan.tibetanminicommons.utils.MD5Utils;
import com.ysdz.tibetan.tibetanmini.user.dao.UsersMapper;
import com.ysdz.tibetan.tibetanmini.user.service.ConsumerService;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class ConsumerServiceImpl implements ConsumerService {

    @Autowired
    private AuthMapper authMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UsersMapper usersMapper;

    @Override
    public ReturnMsg getUserList() {
        return new ReturnMsg(ReturnMsg.SUCCESS_CODE, "获取成功！", usersMapper.selectAll());
    }

    @Override
    public Consumer findUserByUsername(String username) {
        Example example = new Example(Consumer.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username",username);
        List<Consumer> consumer = usersMapper.selectByExample(example);
        return consumer.get(0);
    }

    @Override
    public List<Auth> findAuthByUserId(Long id) { return authMapper.selectAuthListByUserId(id); }

    @Override
    public List<Role> findRoleByUserId(Long userId) {
        return roleMapper.selectRoleListByUserId(userId);
    }

    @Override
    public void authentication(String userId) {
        RedisUtils.set("authentication:" + userId, "用户Id:" + userId + "正在申请成为救援队员");
    }

    @Override
    public boolean passAuthentication(String userId) {
        Boolean flag = RedisUtils.hasKey("authentication:" + userId);
        if (!flag) {
            return false;
        }
        //1.修改身份
        //2.删除缓存
        RedisUtils.delete("authentication:" + userId);
        return true;
    }

    @Override
    public void updateRole(UserRole userRole) {

    }

    @Transactional
    public ReturnMsg userRegist(String name, String pwd) {
        synchronized (this) {
            // 判断该用户名是否被注册
            Consumer consumer = usersMapper.queryUserByName(name);

            if (consumer == null) {
                // 加密 密码
                String md5Pwd = MD5Utils.md5(pwd);

                consumer = new Consumer();
                consumer.setUsername(name);
                consumer.setPassword(md5Pwd);
                consumer.setUserRegtime(new Date());
                int i = usersMapper.insertUseGeneratedKeys(consumer);

                if (i > 0) {
                    return new ReturnMsg(ReturnMsg.SUCCESS_CODE, "注册成功!", consumer);
                } else {
                    return new ReturnMsg(ReturnMsg.SUCCESS_CODE, "注册失败!", null);
                }
            } else {
                return new ReturnMsg(ReturnMsg.SUCCESS_CODE, "用户名已被注册!", null);
            }
        }
    }

    public ReturnMsg checkLogin(String name, String pwd) {
        // 查询用户信息
        Consumer consumer = usersMapper.queryUserByName(name);

        if (consumer == null){
            // 用户名不存在   返回出错数据
            return new ReturnMsg(ReturnMsg.SUCCESS_CODE, "登录失败, 用户名不存在！", null);
        }else{
            // 密码解密并校验
            String md5Pwd = MD5Utils.md5(pwd);
            if (md5Pwd.equals(consumer.getPassword())){
                // 验证成功 生成token
                JwtBuilder builder = Jwts.builder();

                HashMap<String,Object> map = new HashMap<>();
                map.put("key1","value1");
                map.put("key2","value2");

                String token = builder.setSubject(name)                     //主题，就是token中携带的数据
                        .setIssuedAt(new Date())                            //设置token的生成时间
                        .setId(consumer.getUserId() + "")                       //设置用户id为token  id
                        .setClaims(map)                                     //map中可以存放用户的角色权限信息
                        .setExpiration(new Date(System.currentTimeMillis() + 9*60*1000)) //设置token过期时间
                        .signWith(SignatureAlgorithm.HS256, "123456")     //设置加密方式和加密密码
                        .compact();

                return new ReturnMsg(ReturnMsg.SUCCESS_CODE, token, consumer);
            }else{
                // 密码错误
                return new ReturnMsg(ReturnMsg.SUCCESS_CODE, "密码错误！", null);
            }
        }
    }
}
